package com.jing.yuntuku.controller;

import com.jing.yuntuku.annotation.AuthCheck;
import com.jing.yuntuku.config.UserConstant;
import com.jing.yuntuku.exception.BusinessException;
import com.jing.yuntuku.exception.ErrorCode;
import com.jing.yuntuku.model.dto.file.UploadPictureResult;
import com.jing.yuntuku.result.BaseResponse;
import com.jing.yuntuku.service.impl.FileManager;
import com.jing.yuntuku.utils.AliOssUtil;
import com.jing.yuntuku.utils.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/test")
@Api(tags = "通用接口")
public class CommonController {

    @Resource
    private AliOssUtil aliOssUtil;

    @Resource
    private FileManager fileManager;

    @PostMapping("/sccs")
    public BaseResponse sccs(@RequestParam("file") MultipartFile file, String url) {
        UploadPictureResult uploadPictureResult = fileManager.uploadFileAndGetInfo(file, url);
        System.out.println(uploadPictureResult + "00000000000000000000000000000000000");
        return ResultUtils.success("成功");
    }


    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("文件上传接口")
    @PostMapping("/upload")
    public BaseResponse<?> upload(MultipartFile file) {
        log.info("文件上传：{}", file);

        try {
            //原文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            //创建新文件名称
            String s = UUID.randomUUID() + substring;
            String upload = aliOssUtil.upload(file.getBytes(), s);
            //文件请求路径
            return ResultUtils.success(upload);
        } catch (IOException e) {
            log.info("文件上传异常：{}", e.getMessage());
        }
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "文件上传失败");
    }

    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("文件下载接口")
    @GetMapping("/download")
    public void download(@RequestParam String fileName, HttpServletResponse response) {
        try {
            // 设置响应头，告诉浏览器这是一个下载文件
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/octet-stream");

            // 从OSS获取文件字节流
            byte[] fileBytes = aliOssUtil.download(fileName);

            // 将文件字节流写入响应输出流
            OutputStream os = response.getOutputStream();
            os.write(fileBytes);
            os.flush();
            os.close();

        } catch (Exception e) {
            log.error("文件下载异常：{}", e.getMessage());
            // 可以根据需要设置错误响应
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件下载异常");
        }
    }

}
